<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" :width="1500"  destroy-on-close @closed="$emit('closed')" align-center>
        <el-button type="primary" @click="print">打印</el-button>
        <el-button type="primary" color="#6074e8" @click="to_export">导出</el-button>
        <el-main class="printMain" ref="printMain">
            <div class="title">报关清单</div>
            <table border="1" style="border-collapse: collapse; width: 100%;">
                <thead>
                    <tr style="height:32px;line-height: 32px;">
                        <th class="table_border" colspan="3">发货单号</th>
                        <th class="table_border" colspan="4">{{detail.send_code}}</th>
                    </tr>
                    <tr style="height:32px;line-height: 32px;">
                        <th class="table_border" style="width: 150px">品名</th>
                        <th class="table_border">供应商</th>
                        <th class="table_border">花型</th>
                        <th class="table_border">匹数</th>
                        <th class="table_border">体积</th>
                        <th class="table_border">总体积</th>
                        <th class="table_border">均重</th>
                        <th class="table_border">总重量</th>
                        <th class="table_border">总码数</th>
                        <th class="table_border">总米数</th>
                        <th class="table_border">成本价</th>
                    </tr>
                </thead>
                <tbody>
                    <template v-for="(goodsGroup, goodsIndex) in order_detail" :key="goodsIndex">
                        <template v-for="(colorGroup, colorIndex) in goodsGroup.colorGroups" :key="colorIndex">
                            <tr v-for="(item, itemIndex) in colorGroup.items" :key="itemIndex">
                                <td class="table_border" :rowspan="goodsGroup.totalRows" v-if="colorIndex === 0 && itemIndex === 0">
                                    {{goodsGroup.goods_name}}
                                </td>
                                <td class="table_border" :rowspan="goodsGroup.totalRows" v-if="colorIndex === 0 && itemIndex === 0">
                                    {{goodsGroup.apply_name || '-'}}
                                </td>
                                <td class="table_border" :rowspan="goodsGroup.totalRows" v-if="colorIndex === 0 && itemIndex === 0">
                                    {{goodsGroup.flower}}
                                </td>
                                <td class="table_border" :rowspan="goodsGroup.totalRows" v-if="colorIndex === 0 && itemIndex === 0">
                                    {{goodsGroup.total_count}}
                                </td>
                                <td class="table_border" :rowspan="goodsGroup.totalRows" v-if="colorIndex === 0 && itemIndex === 0">
                                    {{goodsGroup.volume}}
                                </td>
                                <td class="table_border" :rowspan="goodsGroup.totalRows" v-if="colorIndex === 0 && itemIndex === 0">
                                    {{goodsGroup.total_volume_sum}}
                                </td>
                                <td class="table_border" :rowspan="goodsGroup.totalRows" v-if="colorIndex === 0 && itemIndex === 0">
                                    {{(goodsGroup.total_weight_sum / goodsGroup.total_count).toFixed(2) }}
                                </td>
                                <td class="table_border" :rowspan="goodsGroup.totalRows" v-if="colorIndex === 0 && itemIndex === 0">
                                    {{goodsGroup.total_weight_sum}}
                                </td>
                                <td class="table_border" :rowspan="goodsGroup.totalRows" v-if="colorIndex === 0 && itemIndex === 0">
                                    {{goodsGroup.total_number_sum}}
                                </td>
                                <td class="table_border" :rowspan="goodsGroup.totalRows" v-if="colorIndex === 0 && itemIndex === 0">
                                    {{(goodsGroup.total_meter_sum).toFixed(2)}}
                                </td>
                                <td class="table_border" :rowspan="goodsGroup.totalRows" v-if="colorIndex === 0 && itemIndex === 0">
                                </td>
                            </tr>
                        </template>
                        <!-- 品名合计行已移除，不需要每个商品下面都放小计 -->
                    </template>
                </tbody>
                <!-- 汇总表总合计行 -->
                <tfoot>
                    <tr style="background-color: #b1d0f0; font-weight: bold;">
                        <td class="table_border"></td>
                        <td class="table_border"></td>
                        <td class="table_border" style="text-align: center;">总计</td>
                        <td class="table_border">{{summaryGrandTotals.total_count}}</td>
                        <td class="table_border"></td>
                        <td class="table_border">{{summaryGrandTotals.total_volume_sum}}</td>
                        <td class="table_border"></td><!-- {{(summaryGrandTotals.total_weight_sum / summaryGrandTotals.total_count).toFixed(2)}} -->
                        <td class="table_border">{{summaryGrandTotals.total_weight_sum}}</td>
                        <td class="table_border">{{summaryGrandTotals.total_number_sum}}</td>
                        <td class="table_border">{{summaryGrandTotals.total_meter_sum}}</td>
                        <td class="table_border"></td>
                    </tr>
                </tfoot>
            </table>
        </el-main>
	</el-dialog>
</template>

<script>
import print from '@/utils/print'
export default {
	emits: ['success', 'closed'],
	data() {
        return {
            dialog: {
                client: false
            },
            mode: "add",
            titleMap: {
                print: '打印',
            },
            visible: false,
            id: "",
            detail: {},
            order_detail: [],
            summary_detail: [], // 按品名汇总的数据，花型用/合并，数量合计
            summaryGrandTotals: { // 汇总表的总合计
                total_count: 0, // 总件数
                total_number_sum: 0, // 总总数量
                total_meter_sum: 0, // 总金额
                total_weight_sum: 0, // 总重量
                total_volume_sum: 0, // 总体积
            }
        }
    },
	mounted() {
	},
	methods: {
        print(){
            const fileName = this.detail.send_code ? `报关清单_${this.detail.send_code}` : '报关清单';
            print(this.$refs.printMain, { title: fileName });
            setTimeout(()=>{
                this.visible = false
            },500)
        },
		//显示
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},
        async setData(data) {
            this.id = data.id
            var res = await this.$API.ware.ware.send.detail.get({id: data.id});
            this.detail = res.data;
            // 先创建一个临时对象，用于统计相同goods_name、flower和color的数量和合计值
            const uniqueMap = new Map()
            // 遍历数据，合并相同goods_name、flower和color的数据
            res.data.detail.forEach(item => {
                const key = `${item?.inspect.goods_name}_${item?.inspect.flower}_${item?.inspect.color_en}`
                if (!uniqueMap.has(key)) {
                    // 如果是新的组合，创建新对象
                    uniqueMap.set(key, {
                        goods_id: item?.inspect.goods_id,
                        goods_name: item?.inspect.goods_name,
                        goods_code: item?.inspect.goods_code,
                        apply_name: item?.inspect.apply_name, // 供应商名称
                        flower: item?.inspect.flower,
                        color: item?.inspect.color_en,
                        volume: Number(item.volume),
                        unit_name: "码",
                        number: 1, // 初始数量为1
                        total_meter: Number(item?.inspect?.meter) || 0,
                        total_number: Number(item?.inspect?.code_number) || 0,
                        weight: Number(item?.inspect?.net_weight) || 0,
                        total_weight: Number(item?.inspect?.net_weight) || 0,
                        total_volume: Number(item.volume) || 0,
                        remark: item.remark,
                    })
                } else {
                    // 如果已存在该组合，累加数量和合计值
                    const existingItem = uniqueMap.get(key)
                    existingItem.number += 1
                    existingItem.total_number += Number(item?.inspect?.code_number) || 0
                    existingItem.total_meter += Number(item?.inspect?.meter) || 0
                    existingItem.total_weight += Number(item?.inspect?.net_weight) || 0
                    existingItem.total_volume += Number(item.volume) || 0
                }
            })
            // 将Map转换为数组
            let array = Array.from(uniqueMap.values()).map(item => ({
                ...item,
                equal_weight: item.number > 0 ? (item.total_weight / item.number).toFixed(2) : '0.00', // 计算平均重
                equal_code: item.number > 0 ? (item.total_number / item.number).toFixed(2) : '0.00', // 计算均码
                total_number: (item.total_number).toFixed(2), // 格式化总码数
                total_meter: (item.total_meter).toFixed(2), // 格式化总码数
                total_weight: (item.total_weight).toFixed(2), // 格式化总码数
                total_volume: Number(item.volume).toFixed(2), // 格式化体积
            }))
            // 按goods_name、flower和color分组数据，并计算合计
            this.order_detail = this.groupDataByGoodsAndFlower(array)
            this.summary_detail = this.createSummaryData(array)
            this.calculateSummaryGrandTotals()
        },
        // 计算汇总表的总合计
        calculateSummaryGrandTotals() {
            let grandTotalCount = 0
            let grandTotalNumber = 0
            let grandTotalMeter = 0
            let grandTotalWeight = 0
            let grandTotalVolume = 0
            
            // 直接从order_detail数组中累加各个品名分组的小计值
            this.order_detail.forEach(goodsGroup => {
                grandTotalCount += goodsGroup.total_count
                grandTotalNumber += parseFloat(goodsGroup.total_number_sum || 0)
                grandTotalMeter += parseFloat(goodsGroup.total_meter_sum || 0)
                grandTotalWeight += parseFloat(goodsGroup.total_weight_sum || 0)
                grandTotalVolume += parseFloat(goodsGroup.total_volume_sum || 0)
            })
            
            this.summaryGrandTotals = {
                total_count: grandTotalCount,
                total_number_sum: grandTotalNumber.toFixed(2),
                total_meter_sum: grandTotalMeter.toFixed(2),
                total_weight_sum: grandTotalWeight.toFixed(2),
                total_volume_sum: grandTotalVolume.toFixed(2),
            }
        },
        // 创建按goods_name汇总的数组，合并花型并用/分隔，合计数量
        createSummaryData(data) {
            const summaryMap = new Map();
            
            // 遍历数据，按goods_name分组，合并花型并合计数量
            data.forEach(item => {
                const goodsName = item.goods_name;
                
                if (!summaryMap.has(goodsName)) {
                    summaryMap.set(goodsName, {
                        goods_id: item.goods_id,
                        goods_name: goodsName,
                        goods_code: item.goods_code,
                        flowers: new Set(), // 使用Set存储唯一的花型
                        total_count: 0, // 合计件数
                        total_number_sum: 0, // 合计总数量
                        total_meter_sum: 0, // 合计米数
                        total_weight_sum: 0, // 合计重量
                        total_volume_sum: 0, // 合计体积
                        total_equal_weight_sum: 0, // 合计均重
                        total_equal_code_sum: 0, // 合计均码
                        unit_name: item.unit_name
                    });
                }
                
                const summary = summaryMap.get(goodsName);
                summary.flowers.add(item.flower); // 添加花型到Set中
                summary.total_count += item.number;
                summary.total_number_sum += parseFloat(item.total_number);
                summary.total_meter_sum += parseFloat(item.total_meter);
                summary.total_weight_sum += parseFloat(item.total_weight);
                summary.total_volume_sum += parseFloat(item.total_volume || 0);
                summary.total_equal_weight_sum += parseFloat(item.equal_weight || 0);
                summary.total_equal_code_sum += parseFloat(item.equal_code || 0);
            });
            
            // 转换为数组，处理花型合并和格式化数值
            const result = Array.from(summaryMap.values()).map(item => ({
                ...item,
                flowers: Array.from(item.flowers).join('/'), // 用/分隔合并花型
                total_number_sum: item.total_number_sum.toFixed(2),
                total_meter_sum: item.total_meter_sum.toFixed(2),
                total_weight_sum: item.total_weight_sum.toFixed(2),
                total_volume_sum: item.total_volume_sum.toFixed(2),
                equal_weight: item.total_equal_weight_sum.toFixed(2),
                equal_code: item.total_equal_code_sum.toFixed(2)
            }));
            
            return result;
        },
        // 按goods_name分组数据，花型用/合并
        groupDataByGoodsAndFlower(data) {
            // 创建一个Map来存储每个goods_name的分组
            const goodsMap = new Map();
            
            // 遍历数据，按goods_name分组，合并花型
            data.forEach(item => {
                const goodsName = item.goods_name;
                
                // 如果goods_name不存在于Map中，创建新的goods分组
                if (!goodsMap.has(goodsName)) {
                    goodsMap.set(goodsName, {
                        goods_id: item.goods_id,
                        goods_name: goodsName,
                        goods_code: item.goods_code,
                        apply_name: item.apply_name, // 供应商信息
                        volume: item.volume || 0, // 体积
                        flowers: new Set(), // 使用Set存储唯一的花型
                        colorGroups: [], // 直接在品名级别按颜色分组
                        totalRows: 0, // 该品名的总行数(包括明细和合计行)
                        total_count: 0, // 合计匹数
                        total_number_sum: 0, // 合计总码数
                        total_meter_sum: 0, // 合计总米数
                        total_weight_sum: 0, // 合计重量
                        total_volume_sum: 0, // 合计总体积
                        total_equal_weight_sum: 0, // 合计均重
                        total_equal_code_sum: 0 // 合计均码
                    });
                }
                
                const goodsGroup = goodsMap.get(goodsName);
                goodsGroup.flowers.add(item.flower); // 添加花型到Set中
                
                // 查找当前color的分组
                let colorGroup = goodsGroup.colorGroups.find(group => group.color === item.color);
                
                // 如果color分组不存在，创建新的color分组
                if (!colorGroup) {
                    colorGroup = {
                        color: item.color,
                        items: []
                    };
                    goodsGroup.colorGroups.push(colorGroup);
                }
                
                // 将当前项添加到color分组中
                colorGroup.items.push(item);
                // 更新品名的合计值
                goodsGroup.total_count += item.number;
                goodsGroup.total_weight_sum += parseFloat(item.total_weight);
                goodsGroup.total_number_sum += parseFloat(item.total_number || 0);
                goodsGroup.total_meter_sum += parseFloat(item.total_meter || 0);
                goodsGroup.total_equal_weight_sum += parseFloat(item.equal_weight);
            });
            
            // 计算每个goods分组的总行数和合并花型
            const result = Array.from(goodsMap.values());
            result.forEach(goodsGroup => {
                // 合并花型，用/分隔
                goodsGroup.flower = Array.from(goodsGroup.flowers).join('/');
                
                // 计算每个goods分组的总行数
                goodsGroup.totalRows = goodsGroup.colorGroups.reduce((total, colorGroup) => total + colorGroup.items.length, 0);
                
                // 计算总体积 = 匹数 * 体积（体积使用每个品名的第一条的值）
                goodsGroup.total_volume_sum = (goodsGroup.total_count * parseFloat(goodsGroup.volume)).toFixed(2);
                
                // 格式化合计值
                goodsGroup.total_number_sum = (goodsGroup.total_number_sum).toFixed(2);
                goodsGroup.total_weight_sum = (goodsGroup.total_weight_sum).toFixed(2);
                
                // 计算品名合计的总均重和总均码
                goodsGroup.equal_weight = goodsGroup.total_equal_weight_sum.toFixed(2);
            });
            
            return result;
        },


        async to_export(){
            var res = await this.$API.ware.ware.comparison_export.get({id: this.id})
            if (res.code == 1) {
				this.$message.success("导出成功");
				window.location.href = res.data.url
			} else {
				this.$alert(res.message, "提示", {type: "error"});
			}
        },
        
	}
}
</script>

<style lang="scss" scoped>
.printMain{
    .title {
        font-size: 20px;
        text-align: center;
        font-weight: bold;
        margin-bottom: 10px;
    }
    td{
        text-align: center;
    }
    .table_border{
        width: 100px;
        height: 32px;
    }
    table{
        tbody{
            font-size: 13px;
            tr {
                page-break-inside: avoid;
                -webkit-region-break-inside: avoid; 
            }
            tr:last-child{
                page-break-after: avoid;
                
            }
        }
    } 
}
</style>
